package com.bdqn.ch02.SL;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * CollectMessageUpd
 * 示例 6  删除手机收藏信息
 * @aurhor Administrator  whs
 * @since 2024/6/27
 */
public class CollectMessageDel {

    public static void main(String[] args) {
         // 得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            //   从 DOM 工厂获得 DOM 解析器
            DocumentBuilder db = dbf.newDocumentBuilder();

            //   解析XML文档 得到一个 Document 即DOM 树
            Document doc = db.parse("D:\\Frame\\frames\\web\\collectMessage.xml");

             // 1. 找到修改的 Brand 节点
            NodeList list = doc.getElementsByTagName("Brand");

            for (int i = 0; i < list.getLength(); i++) {
                Element brandElement = (Element)list.item(i);
                String brandName = brandElement.getAttribute("name");
                // 判断如果值为 SAMSUNG，则进行删除
                if (brandName.equals("SAMSUNG")){

                    brandElement.getParentNode().removeChild(brandElement);  // 先找到父节点 然后 删除这个子节点
                }

            }


            //   保存 XML 文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);

            //  设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result = new StreamResult(new FileOutputStream("D:\\Frame\\frames\\web\\collectMessage.xml"));

            //   把 DOM 树转换为 XML 文件
            transformer.transform(domSource,result);

        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }
}
